<!--
  * 代理商表
  *
  * @Author:    zwd
  * @Date:      2025-01-23 04:08:26
-->
<template>
  <a-modal
    :title="form.id ? '代理商信息修改' : '新增代理商'"
    :width="800"
    :open="visibleFlag"
    @cancel="onClose"
    :maskClosable="false"
    :destroyOnClose="true"
  >
    <!-- :label-col="{ span: 6 }" -->
    <a-form ref="formRef" :model="form" :rules="rules" label-align="right" layout="vertical">
      <template v-if="form.id">
        <a-row>
          <a-col :span="8">
            <div style="margin-bottom: 16px"><span style="font-weight: normal">登录账号：</span>{{ form.no }}</div>
          </a-col>
          <a-col :span="8">
            <div style="margin-bottom: 16px"><span style="font-weight: normal">公司名称：</span>{{ form.companyName }}</div>
          </a-col>
          <a-col :span="8">
            <div style="margin-bottom: 16px"><span style="font-weight: normal">分润提现：</span> {{ getHandleTypeLabel(form.profitDrawType) }}</div>
          </a-col>
        </a-row>
      </template>
      <div class="section-title">基础信息</div>
      <a-row :gutter="20">
        <a-col :span="12" v-if="!form.id">
          <a-form-item label="公司名称" name="companyName">
            <a-input v-model:value="form.companyName" placeholder="请输入" :disabled="!!form.id" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="公司简称" name="companyAbbrName">
            <a-input v-model:value="form.companyAbbrName" placeholder="请输入" :disabled="!!form.id" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系人" name="name">
            <a-input v-model:value="form.name" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系方式" name="phone">
            <a-input v-model:value="form.phone" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="城市" name="areaCode">
            <area-cascader v-model:value="form.areaCode" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="地址" name="addr">
            <a-input v-model:value="form.addr" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="授权业务" name="authBussType">
            <a-select v-model:value="form.authBussType" :disabled="!!form.id" :options="AGENT_AUTH_BUSS_TYPE" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态" name="status">
            <a-select v-model:value="form.status" :options="ZZB_AGENT_NO_STATUS" placeholder="请选择状态" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="开户业务人员" name="exhibitionId">
            <CustomSelect
              v-model:value="form.exhibitionId"
              :placeholder="'请选择开户业务人员'"
              :api="exhibitionApi.queryPage"
              queryParamKey="nameLeftLike"
              :initParams="{ exhibitionId: form.exhibitionId }"
              :queryParams="exhibitionParams"
              :response-adapter="filterParams"
              labelField="name,no"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="!form.id">
          <a-form-item label="分润提现" name="profitDrawType">
            <SmartEnumSelect width="100%" v-model:value="form.profitDrawType" enumName="PROFIT_WITHDRAWAL_TYPE_ENUM" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="form.id">
          <a-form-item label="分润提现起始金额" name="profitMinDraw">
            <a-input v-model:value="form.profitMinDraw" placeholder="请输入" />
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 账号设置部分只在新增时显示 -->
      <template v-if="!form.id">
        <a-divider>账号设置</a-divider>
        <a-row :gutter="20">
          <a-col :span="12">
            <a-form-item label="账号类型" name="noType">
              <SmartEnumSelect width="100%" v-model:value="form.noType" enumName="ZZB_NO_TYPE_ENUM" placeholder="请选择账号类型" />
              <span class="note">账号设置为手机号的，将推送验证码，登录成功后该账号生效</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="登录账号" name="no">
              <a-input v-model:value="form.no" placeholder="请输入账号" />
              <span class="note">注意：非手机号账号类型，需大于或小于11位</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="密码" name="pwd">
              <a-input v-model:value="form.pwd" placeholder="请输入密码" :maxlength="20" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="密码确认" name="confirmPwd">
              <a-input v-model:value="form.confirmPwd" placeholder="请输入密码" :maxlength="20" />
            </a-form-item>
          </a-col>
        </a-row>
      </template>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onReset">重置</a-button>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { reactive, ref } from 'vue'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { agentApi } from '/src/api/business/b-agent/agent/agent-api.js'
  import { smartSentry } from '/@/lib/smart-sentry'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import AreaCascader from '/@/components/business/b-operation/area-cascader/index.vue'
  import { STATUS_ENUM, PROFIT_WITHDRAWAL_TYPE_ENUM } from '/src/constants/business/b-agent/agent/agent-const'
  import { exhibitionApi } from '/@/api/business/b-agent/exhibition/exhibition-api.js'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { ZZB_AUTH_BUSS_TYPE_ENUM, ZZB_ENABLE_STATUS_ENUM, ZZB_EXHIBITION_STATUS_ENUM } from '/@/constants/system/system-const.js'
  import { isMulPassword, maxDecimals } from '/@/utils/validate'
  import {
    ZZB_AGENT_NO_STATUS, // 代理商状态
    AGENT_AUTH_BUSS_TYPE, // 授权业务
  } from '/@/constants/dict'
  import { isEmpty } from 'lodash'
  import { myToFixed } from '/@/utils/common'

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList'])

  function getHandleTypeLabel(value) {
    for (const key in PROFIT_WITHDRAWAL_TYPE_ENUM) {
      if (PROFIT_WITHDRAWAL_TYPE_ENUM[key].value === value) {
        return PROFIT_WITHDRAWAL_TYPE_ENUM[key].desc
      }
    }
  }

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false)

  async function show(rowData) {
    Object.assign(form, formDefault)
    if (rowData && rowData.id) {
      try {
        SmartLoading.show()
        const response = await agentApi.findOne({ id: rowData.id })
        if (response && response.data) {
          Object.assign(form, response.data)
          if (form.profitMinDraw) {
            form.profitMinDraw = form.profitMinDraw / 100
          }
          // 新增：获取开户业务人员信息并回填
          // try {
          //   if (form.exhibitionId) {
          //     await exhibitionApi.findId({ id: form.exhibitionId })
          //   }
          // } catch (e) {
          //   form.exhibitionId = undefined
          // }
        }
      } catch (error) {
        smartSentry.captureError(error)
      } finally {
        SmartLoading.hide()
      }
    }
    visibleFlag.value = true
  }

  function onClose() {
    Object.assign(form, formDefault)
    visibleFlag.value = false
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()

  const formDefault = {
    id: undefined,
    no: undefined, //代理商账号
    noType: undefined, //代理商账号类型，0手机号，1企业代码
    pwd: undefined, //代理商密码
    companyName: undefined, //公司名称
    companyAbbrName: undefined, //公司简称
    name: undefined, //联系人
    phone: undefined, //联系方式
    areaCode: undefined, //城市，所属区/县ID
    addr: undefined, //地址
    authBussType: undefined, //授权业务，0全部，1开设代理商，2开商户
    status: STATUS_ENUM.NORMAL.value, //状态，0正常使用，1禁止开代理商，2禁止开商户，3禁止操作人员登录，4系统停止使用，5停止全部收款，6全部禁用
    exhibitionId: undefined, //开户业务人员
    profitDrawType: undefined, //分润提现，0统一提现，1逐级提现
    profitMinDraw: undefined, //代理商分润提现起始金额，单位分
    defaultedFlag: undefined, //是否默认参数，0否，1是
  }

  let form = reactive({ ...formDefault })
  const checkPhoneNumbers = (rule, value, callback) => {
    // 如果值为空，直接返回
    if (!value) {
      callback('手机号必填')
    }

    // 校验手机号码格式（示例：简单的正则表达式）
    const phoneRegex = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[0,1,4-9])|(?:5[0-3,5-9])|(?:6[2,5-7])|(?:7[0-8])|(?:8[\d])|(?:9[0-3,5-9]))\d{8}$/ // 简单的中国大陆手机号码正则
    if (!phoneRegex.test(value)) {
      callback('手机号码格式不正确')
    } else {
      callback() // 校验通过
    }
  }

  const validateProfitMinDraw = (rule, value, callback) => {
    if (value === undefined || value === null) {
      callback(new Error('分润提现起始金额必填'))
    } else if (value <= 0) {
      callback(new Error('分润提现起始金额必须大于0'))
    } else {
      callback()
    }
  }

  const rules = {
    no: [{ required: !form.id, message: '代理商账号 必填' }],
    noType: [{ required: !form.id, message: '代理商账号类型，0手机号，1企业代码 必填' }],
    pwd: [
      { required: !form.id, message: '代理商密码 必填' },
      {
        validator: isMulPassword,
      },
    ],
    companyName: [{ required: true, message: '公司名称 必填' }],
    companyAbbrName: [{ required: true, message: '公司简称 必填' }],
    name: [{ required: true, message: '联系人 必填' }],
    exhibitionId: [{ required: true, message: '开户业务人员 必填' }],
    phone: [{ validator: checkPhoneNumbers }],
    areaCode: [{ required: true, message: '城市，所属区/县ID 必填' }],
    addr: [{ required: true, message: '地址 必填' }],
    authBussType: [{ required: true, message: '授权业务，0全部，1开设代理商，2开商户 必填' }],
    status: [
      { required: true, message: '状态，0正常使用，1禁止开代理商，2禁止开商户，3禁止操作人员登录，4系统停止使用，5停止全部收款，6全部禁用 必填' },
    ],
    profitDrawType: [{ required: true, message: '分润提现，0统一提现，1逐级提现 必填' }],
    profitMinDraw: [
      { required: true, message: '代理商分润提现起始金额，单位分 必填' },
      { validator: validateProfitMinDraw, trigger: blur },
      { validator: maxDecimals },
    ],
  }

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      save()
    } catch (err) {
      console.log(err)
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }
  const submitLoading = ref(false)
  // 新建、编辑API
  async function save() {
    submitLoading.value = true
    try {
      form.profitMinDraw = myToFixed(form.profitMinDraw * 100, 0)
      if (form.id) {
        await agentApi.updateAgent(form)
      } else {
        await agentApi.addAgent(form)
      }
      message.success('操作成功')
      emits('reloadList')
      onClose()
    } catch (err) {
      console.log(err)

      form.profitMinDraw = form.profitMinDraw / 100
      message.error('保存失败')
      smartSentry.captureError(err)
    } finally {
      submitLoading.value = false
    }
  }

  const onReset = () => {
    // 1.重置表单验证状态（不重置数据）
    formRef.value?.resetFields()

    // 2.仅重置非ID字段（解构排除id）
    const { id, companyAbbrName, companyName, profitDrawType, ...resettableData } = formDefault
    Object.assign(form, resettableData)
  }

  const exhibitionParams = reactive({
    showDeletedFlag: false,
    status: 0, //正常使用
    userStatus: 1, //启用
    authBussType: 0, //    开商户,
  })
  const filterParams = (val) => {
    val.data?.forEach((element, index, arr) => {
      arr[index].disabled =
        (element.status !== ZZB_EXHIBITION_STATUS_ENUM.EXHIBITION_STATUS_NORMAL.value &&
          element.auth !== ZZB_AUTH_BUSS_TYPE_ENUM.AUTH_BUSS_TYPE_OPEN_AGENT.value &&
          element.userStatus !== ZZB_ENABLE_STATUS_ENUM.ENABLE_STATUS.value) ||
        element.userStatus == null
    })
    return val
  }

  defineExpose({
    show,
  })
</script>

<style scoped>
  .section-title {
    font-size: 14px;
    font-weight: 500;
    margin: 24px 0 16px;
    color: #1f1f1f;
    position: relative;
    padding-left: 10px;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background-color: #1890ff;
    }
  }
  .note {
    color: red;
    font-size: 12px;
  }
</style>
